import React from 'react';
import { message } from 'antd';
import { isSuccess } from '@/utils/request';
import moment from 'moment';

import modelType from '@/pages/SalaryManage/constant/commonModelType';
import { salaryRecheck } from '@/services/salaryManage/salaryCalculate';
import NumberFormatter from '@/pages/SalaryManage/components/NumberFormatter';

function* getState(select, namespace) {
    return yield select(state => state[namespace]);
}

function* searchPostData(select, namespace) {
    const currentState = yield* getState(select, namespace);

    const searchCondition = {
        searchModel: currentState.searchModel,
        pagination: currentState.pagination || {
            current: 1,
            pageSize: 10
        }
    };

    const { searchModel, pagination } = searchCondition;

    return {
        page: {
            pageNo: pagination.current,
            pageSize: pagination.pageSize
        },
        ...searchModel
    };
}

function getMomentByYearAndMonth(year, month) {
    return year && month ? moment(year * 100 + month, 'YYYYMM') : null;
}

function generateSubTitle(postData) {
    const titleArray = [];
    const { startYear, startMonth, endYear, endMonth } = postData;
    if (startYear && startMonth) {
        titleArray.push(`${startYear}-${(startMonth < 10 ? '0' : '') + startMonth}`);
    }

    if (endYear && endMonth) {
        titleArray.push(`${endYear}-${(endMonth < 10 ? '0' : '') + endMonth}`);
    }
    return titleArray?.length > 0 ? `（${titleArray.join(' ~ ')}）` : '';
}

const generateModel = ({ namespace, service }) => ({
    namespace,
    state: {
        searchModel: {},
        pageLoading: false,

        tableColumns: () => [],
        dataSource: [],
        columnsRender: columns =>
            columns.map(column =>
                column.columnType === 2
                    ? {
                          ...column,
                          render(text /* , record */) {
                              return <NumberFormatter value={text} negativeColor color={column.colorControl === 1} />;
                          }
                      }
                    : column
            ),
        dataSourceRender: dataSource => dataSource,
        summaryFieldsRender: () => null,
        pagination: {
            current: 1,
            pageSize: 10
        }
    },
    reducers: {
        [modelType.SET_MULTI_STORE](state, action) {
            return {
                ...state,
                ...action.payload
            };
        },

        [modelType.SET_SEARCH_CONDITION](state, action) {
            const { searchModel } = state;
            return {
                ...state,
                searchModel: {
                    ...searchModel,
                    ...action.payload
                }
            };
        },

        [modelType.SET_PAGE_INFO](state, action) {
            const { pageSize, total, pageNo: current, rows: dataSource } = action.payload.data;

            const pagination = {
                ...state.pagination,
                pageSize: pageSize || 10,
                current: current || 1,
                total
            };

            return {
                ...state,
                dataSource,
                pagination
            };
        },

        [modelType.SET_PAGINATION](state, action) {
            const pagination = {
                ...state.pagination,
                current: action.payload.current || state.pagination.current,
                pageSize: action.payload.pageSize || state.pagination.pageSize
            };

            return {
                ...state,
                pagination
            };
        }
    },
    effects: {
        // 初始化
        *[modelType.E_INIT](state, { put, call, select, all }) {
            yield put({
                type: modelType.SET_MULTI_STORE,
                payload: { pageLoading: true, searchModel: {} }
            });

            const response = yield call(salaryRecheck.latestSalaryYearMonth, {
                organizationCode: state.payload.organizationCode
            });

            if (isSuccess(response)) {
                const { year, month } = response.data;
                yield put({
                    type: modelType.SET_SEARCH_CONDITION,
                    payload: {
                        period: [getMomentByYearAndMonth(year, month), getMomentByYearAndMonth(year, month)],
                        startYear: year,
                        startMonth: month,
                        endYear: year,
                        endMonth: month,
                        organizationCode: state.payload.organizationCode
                    }
                });
            }

            const postData = yield* searchPostData(select, namespace);
            // 向后台请求【表头】跟【表身】数据
            const [bodyResponse] = yield all([
                // 查询表身数据
                call(service.queryTableBodyData, postData)
            ]);

            let subTitleStr = '';
            if (isSuccess(bodyResponse)) {
                yield put({
                    type: modelType.SET_PAGE_INFO,
                    payload: bodyResponse
                });
                subTitleStr = generateSubTitle(postData);
            } else {
                message.error(`请求表身数据失败：${bodyResponse.msg}`);
            }

            yield put({
                type: modelType.SET_MULTI_STORE,
                payload: {
                    pageLoading: false,
                    subTitle: subTitleStr
                }
            });
        },

        /**
         * 查询
         */
        *[modelType.E_SEARCH](s, { put, call, select, all }) {
            // 设置查询条件
            if (s.payload) {
                yield put({
                    type: modelType.SET_SEARCH_CONDITION,
                    payload: s.payload
                });
            }

            yield put({
                type: modelType.SET_MULTI_STORE,
                payload: { pageLoading: true }
            });
            const postData = yield* searchPostData(select, namespace);

            if (!s?.fromPagination) {
                postData.page.pageNo = 1;
            }

            // 向后台请求【表头】跟【表身】数据
            const [bodyResponse] = yield all([
                // 查询表身数据
                call(service.queryTableBodyData, postData)
            ]);

            let subTitleStr = '';
            if (isSuccess(bodyResponse)) {
                yield put({
                    type: modelType.SET_PAGE_INFO,
                    payload: bodyResponse
                });

                subTitleStr = generateSubTitle(postData);
            } else {
                message.error(`请求表身数据失败：${bodyResponse.msg}`);
            }

            yield put({
                type: modelType.SET_MULTI_STORE,
                payload: {
                    pageLoading: false,
                    subTitle: subTitleStr
                }
            });
        },

        *[modelType.E_TABLE_PAGE_CHANGE](state, { put }) {
            yield put({
                type: modelType.SET_PAGINATION,
                payload: state.payload
            });
            yield put({ type: modelType.E_SEARCH, fromPagination: true });
        },

        *[modelType.E_EXCEL_EXPORT](s, { select, call }) {
            const { page, ...postData } = yield* searchPostData(select, namespace);
            const { companySimpleList } = yield* getState(select, 'finance');
            const organizationName = companySimpleList?.find(
                item => item.organizationCode === postData.organizationCode
            )?.organizationName;

            return yield call(service.excelExport, { ...s.payload, ...postData, organizationName });
        }
    }
});

export default {
    generateModel,
    getState,
    searchPostData
};
